<template>
  <el-drawer :model-value="modelValue"
    :title="mode === 'add' ? $t('announcement.addAnnouncement') : $t('announcement.editAnnouncement')" :size="1200"
    :close-on-click-modal="false" destroy-on-close @update:model-value="$emit('update:modelValue', $event)"
    @close="handleCancel">
    <div class="h-[100%]" v-loading="editDataLoading && mode === 'edit'">
      <el-form ref="formRef" :model="localFormData" :rules="rules" label-width="auto">
        <!-- 标题输入区域 -->
        <div class="flex">
          <el-form-item :label="$t('announcement.announcementTitle')" prop="title" class="mr-[40px] ml-[20px]">
            <el-input v-model="localFormData.title" :placeholder="$t('announcement.placeholders.titleInput')"
              class="w-[472px]" maxlength="50" />
          </el-form-item>
          <!-- 公告类型选择器 -->
          <el-form-item :label="$t('announcement.announcementType')" prop="type">
            <el-select v-model="localFormData.type" :placeholder="$t('announcement.placeholders.typeSelect')"
              class="w-[472px]">
              <el-option :label="$t('announcement.types.upgrade')" value="upgrade" />
              <el-option :label="$t('announcement.types.system')" value="system" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 富文本编辑器区域 -->
        <div class="editor-section">
          <el-form-item :label="$t('announcement.announcementContent')" prop="content" class="ml-[20px] mb-[20px]">
            <div :class="['editor-wrapper', { 'editor-error': showContentError }]" class="w-[100%]">
              <WangEditor
                v-model="localFormData.content"
                mode="default"
                :scrollable="true"
                :height="'calc(100vh - 200px)'"
                :placeholder="$t('announcement.placeholders.contentInput')"
              />
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="props.loadFlag" class="w-[80px]">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { $t } from '@vben/locales';
import WangEditor from '#/components/editor.vue';
import { isWangEditorEmpty, getWangEditorTextLength } from '#/utils/editorUtils';

interface Props {
  modelValue: boolean;
  formData: any;
  mode: 'add' | 'edit';
  loadFlag: boolean;
  editDataLoading?: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);

const formRef = ref<FormInstance>();

// 本地表单数据副本，避免直接修改props
const localFormData = reactive({
  title: '',
  content: '',
  type: '',
  id: undefined
});

// 控制内容错误显示状态
const showContentError = ref(false);

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: $t('announcement.validation.titleRequired'), trigger: 'blur' },
    { min: 1, max: 100, message: $t('announcement.validation.titleLength'), trigger: 'blur' }
  ],
  type: [
    { required: true, message: $t('announcement.validation.typeRequired'), trigger: 'blur' }
  ],
  content: [
    {
      required: true,
      validator: (_rule: any, value: any, callback: any) => {
        if (isWangEditorEmpty(value)) {
          showContentError.value = true;
          callback(new Error($t('announcement.validation.contentRequired')));
        } else {
          // 检查字符长度是否超过12000
          const textLength = getWangEditorTextLength(value);
          if (textLength > 12000) {
            showContentError.value = true;
            callback(new Error($t('announcement.validation.contentTooLong')));
          } else {
            showContentError.value = false;
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ]
};

// 清理内容中可能导致编辑器冲突的HTML
const cleanContentForEditor = (content: string): string => {
  if (!content) return '';

  try {
    // 移除可能导致Slate冲突的HTML标签和属性
    let cleaned = content
      // 移除data-slate-*属性
      .replace(/\s*data-slate-[^=]*="[^"]*"/g, '')
      // 移除data-key属性
      .replace(/\s*data-key="[^"]*"/g, '')
      // 移除contenteditable属性
      .replace(/\s*contenteditable="[^"]*"/g, '')
      // 移除wangEditor相关属性
      .replace(/\s*data-w-e-[^=]*="[^"]*"/g, '');

    return cleaned;
  } catch (error) {
    // console.warn('清理编辑器内容时出错:', error);
    return content;
  }
};

// 监听props变化，同步到本地数据
watch(() => props.formData, (newVal) => {
  if (newVal) {
    // 创建副本并清理内容
    const cleanedData = { ...newVal };
    if (cleanedData.content) {
      cleanedData.content = cleanContentForEditor(cleanedData.content);
    }

    // 更新本地数据
    Object.assign(localFormData, cleanedData);

    // 清除错误状态
    showContentError.value = false;

    if (formRef.value) {
      formRef.value.clearValidate();
    }
  }
}, { deep: true, immediate: true });

// 确认按钮事件
const handleConfirm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    // 传递本地数据副本，而不是props数据
    emit('confirm', { ...localFormData });
  } catch (error) {
    // console.log('表单验证失败:', error);
  }
};

// 取消按钮事件
const handleCancel = () => {
  // 清除错误状态
  showContentError.value = false;

  if (formRef.value) {
    formRef.value.clearValidate();
    formRef.value.resetFields();
  }

  // 重置本地数据为初始状态
  Object.assign(localFormData, {
    title: '',
    content: '',
    type: '',
    id: undefined
  });

  emit('cancel');
};
</script>

<style scoped>
.editor-wrapper {
  position: relative;
}

.editor-wrapper.editor-error :deep(.editor-border-wrap) {
  border: 1px solid #f56c6c;
  border-radius: 4px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}
</style>
